<?php
namespace app\controller;

use app\BaseController;
use OSS\Core\OssException;
use OSS\OssClient;
use think\Db;
use think\facade\Filesystem;
use think\Request;
use think\facade\View;
use think\captcha\facade\Captcha;
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions;
use MicrosoftAzure\Storage\Blob\Models\PublicAccessType;
use MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions;
use think\Image;

class Upload
{

    // 文件上传到本地
    public function upload()
    {
        $file = \think\facade\Request::file('file');
        if ($file) {
            $type = $file->getOriginalMime(); // 文件类型
            if($type != 'application/vnd.ms-excel' && $type != 'video/mp4' && $type != 'image/jpeg' && $type != 'image/jpg' && $type != 'image/gif' && $type != 'image/png' && $type != 'audio/x-m4a' && $type != 'audio/mp3' && $type != 'audio/mpeg' && $type != 'video/mp4' && $type != 'application/pdf' && $type != 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' && $type != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' && $type != 'application/msword' && $type != 'application/octet-stream' && $type != 'video/quicktime'){
                return json(['code'=>500,'data'=>[],'msg'=>'错误的文件类型']);
            }
            // 将文件保存到本地
            $savename = Filesystem::putFile('file', $file);
            chmod(runtime_path() . 'storage/' . $savename, 0777);
            return json(['code'=>200,'data'=>$savename,'msg'=>'上传成功']);

        } else {

            return json(['code'=>500,'data'=>[],'msg'=>lang('NO_SELECT_FILE')]);
        }
    }


    protected $AccountName = 'sparkhrministorage';
    protected $AccountKey = '84SI3ZX/BNXsMl9/e9H8ePA1LSGPjyK46IGo3g2RP2vhyPnfKhtGXEtChEQLzH60HiWEBNKm4HRaOCS+zpN31A==';


    /**
     * 函数用途描述
     * @date: 2019年5月30日
     * @author: Administrator
     * @return:
     */
    public function blob()
    {

        $file = \think\facade\Request::file('file');
        if ($file) {
            $type = $file->getOriginalMime(); // 文件类型
            $name = $file->getOriginalName(); // 文件名

            $icon =  strrchr($name,'.');
            if (!in_array(strtolower($icon),['.jpg', '.png', '.jpeg', '.mp4', '.gif'])) {
                return json(['code'=>500,'data'=>[],'msg'=>'错误的文件类型...']);
            }

            $tmp_name = $file->getPathname(); // 临时存储位置
            if($type != 'video/mp4' && $type != 'image/jpeg' && $type != 'image/jpg' && $type != 'image/gif' && $type != 'image/png'){
                return json(['code'=>500,'data'=>[],'msg'=>'错误的文件类型']);
            }
            return json($this->uploadBlob($tmp_name, $name, $type));

        } else {
            return json(['code'=>500,'data'=>[],'msg'=>lang('NO_SELECT_FILE')]);
        }
    }

    /**
     * 函数用途描述
     * @date: 2019年5月30日
     * @author: Administrator
     * @return:
     */
    public function blobFile()
    {

        $file = \think\facade\Request::file('file');
        if ($file) {
            $type = $file->getOriginalMime(); // 文件类型
            $name = $file->getOriginalName(); // 文件名
            $tmp_name = $file->getPathname(); // 临时存储位置

            if($type != 'application/vnd.ms-excel' && $type != 'video/mp4' && $type != 'image/jpeg' && $type != 'image/jpg' && $type != 'image/gif' && $type != 'image/png' && $type != 'audio/x-m4a' && $type != 'audio/mp3' && $type != 'audio/mpeg' && $type != 'video/mp4' && $type != 'application/pdf' && $type != 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' && $type != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' && $type != 'application/msword' && $type != 'application/octet-stream' && $type != 'video/quicktime'){
                return json(['code'=>500,'data'=>[],'msg'=>'错误的文件类型']);
            }
            return json($this->uploadBlob($tmp_name, $name, $type));

        } else {
            return json(['code'=>500,'data'=>[],'msg'=>lang('NO_SELECT_FILE')]);
        }
    }


    /**
     * 函数用途描述
     * @date: 2019年6月3日
     * @author: Administrator
     * @return:7qh752u=JulEA[y
     */
    public function uploadBlobOld($filePath='', $name='', $type, $folder='uploads')
    {
        $accessKeyId = config('oss.accessKeyId');
        $accessKeySecret = config('oss.accessKeySecret');
        $endpoint = config('oss.endpoint');
        $bucket = config('oss.bucket');

        $fileName = (explode('.',$name));
        $fileName = date('YmdHis').rand(100000,999999).'.'.$fileName[count($fileName)-1];

        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        $object = $folder.'/'.$fileName;

        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            $ossClient->uploadFile($bucket, $object, $filePath);

        } catch(OssException $e) {
            return ['code'=>500, 'data'=>'', 'msg'=>$e->getMessage() . "\n"];
        }

        $uri = 'https://sparkhrminiblob.oss-cn-shanghai.aliyuncs.com/'.$object;

        return ['code'=>200, 'data'=>$uri, 'msg'=>'上传成功'];
    }

    /**
     * 函数用途描述
     * @date: 2019年6月3日
     * @author: Administrator
     * @return:7qh752u=JulEA[y
     */
    public function uploadBlob($path='', $name="", $type, $folder='uploads')
    {
        if (!$path) {

        }
        //blob.core.chinacloudapi.cn
        //blob.core.windows.net

        //$this->AccountKey = urlencode($this->AccountKey);
        $connectionString = "DefaultEndpointsProtocol=https;AccountName=".$this->AccountName.";AccountKey=".$this->AccountKey;

        // Create blob client.
        $blobClient = BlobRestProxy::createBlobService($connectionString);

        $fileToUpload = $path;

        // Create container options object.
        $createContainerOptions = new CreateContainerOptions();


        $createContainerOptions->setPublicAccess(PublicAccessType::CONTAINER_AND_BLOBS);

        // Set container metadata.
        $createContainerOptions->addMetaData("key1", "value1");
        $createContainerOptions->addMetaData("key2", "value2");

        $options = new CreateBlockBlobOptions();
        $options->setContentType($type);

        $containerName = $folder;

        try {

            $content = file_get_contents($path);

            $fileName = (explode('.',$name));
            $fileName = date('YmdHis').rand(100000,999999).'.'.$fileName[count($fileName)-1];
            //Upload blob
            $blobClient->createBlockBlob($containerName, $fileName, $content,$options);
            $uri = 'https://learningspark-resource.lorealchina.com/'.$containerName.'/'.$fileName;

            //鉴黄
            $mime = substr($type,0,5);
//            switch ($mime) {
//                case 'image':
//                    //图片鉴黄
//                    $yellow = new Yellow();
//                    $res = $yellow->imageSync($uri); //微软云路径
//                    break;
//                case 'video':
//                    //视频鉴黄
//                    $yellow = new Yellow();
//                    $res = $yellow->videoSync($path); //本地临时文件路径
//                    break;
//                default:$res = ['code'=>200,'data'=>[],'msg'=>''];
//            }
//            if (isset($res['code']) && $res['code'] !== 200) {
//                return $res;
//            }

            //视频文件获取视频封面
            $cover = '';
            //判断是否视频文件
            if ($mime == 'video') {
                $cover = './uploads/tmp/'.substr($fileName,0,20).'.jpg';//20190603171236733722
                //exec('/usr/bin/ffmpeg -i '.$path.' -y -f mjpeg -ss 1 -t 0.01 -s 750x422 '.$cover);
                exec('/usr/local/ffmpeg/bin/ffmpeg -i '.$path.' -y -f mjpeg -ss 1 -t 0.01 '.$cover);
                //判断是否要旋转图片
                //旋转问题
                $result  = (exec('/usr/local/ffmpeg/bin/ffmpeg '.$path.' -show_streams  | grep rotate'));
                $orientation = 0;
                if (strpos($result, 'TAG:rotate') !== FALSE) {
                    $result = explode("\n", $result);
                    foreach ($result as $line) {
                        if (strpos($line, 'TAG:rotate') !== FALSE) {
                            $stream_info = explode("=", $line);
                            $orientation = $stream_info[1];
                        }
                    }
                }
                if ($orientation > 0) {
                    $image = Image::open($cover);
                    // 对图像使用默认的顺时针旋转90度操作
                    $image->rotate($orientation)->save($cover);
                }
                $cover = \think\facade\Request::domain() . substr($cover,1);
            }

            return ['code'=>200,'data'=>$uri,'cover'=>$cover,'msg'=>'上传成功'];
        }
        catch (ServiceException $e) {
            // Handle exception based on error codes and messages.
            // Error codes and messages are here:
            // http://msdn.microsoft.com/library/azure/dd179439.aspx
            $code = $e->getCode();
            $error_message = $e->getMessage();
            //echo $code.": ".$error_message."<br />";
            return ['code'=>500,'data'=>[],'msg'=>$code.": ".$error_message];
        }
        catch (\InvalidArgumentTypeException $e) {
            // Handle exception based on error codes and messages.
            // Error codes and messages are here:
            // http://msdn.microsoft.com/library/azure/dd179439.aspx
            $code = $e->getCode();
            $error_message = $e->getMessage();
            //echo $code.": ".$error_message."<br />";
            return ['code'=>500,'data'=>[],'msg'=>$code.": ".$error_message];

        }
    }
}